package tp.pr4;

import java.io.FileInputStream;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;

import tp.pr4.cityLoader.CityLoaderFromTxtFile;
import tp.pr4.cityLoader.cityLoaderExceptions.WrongCityFormatException;
import tp.pr4.gui.MainWindow;

/**
 * Aplicación que utiliza las clases de la práctica sobre el mapa
 * que aparece como ejemplo en el enunciado.
 * 
 * @author PuriArenas
 * @y.exclude
 */
public class Main {	
	/**
	 * Creates the city, the engine and finally
	 * starts the simulation
	 * @param args
	 * @throws Exception 
	 */
	static String mapFile;
	public static void main(String[] args) throws Exception {
		boolean swingInterface = true;
		RobotEngine engine;		
			try{
				
				/*
				 * Check the app args
				 */
				Options opt = new Options();
				
				Option hlp = new Option("h","help", false, "Shows this help message");
				opt.addOption(hlp);
				Option intr = new Option("i","interface", true, "The type of interface: console or swing");
				intr.setArgName("type");
				opt.addOption(intr);
				Option map = new Option("m","map", true, "File with the description of the city");
				map.setArgName("mapfile");
				opt.addOption(map);
				
				BasicParser parser = new BasicParser();
				CommandLine cl = parser.parse(opt, args); 
				/*
				 * Checks if the arguments are present
				 */
				if(!cl.hasOption('h') && !cl.hasOption('m') && !cl.hasOption('i')){
					System.err.println("Map file not specified");
			    	System.exit(1);
				}
				if(!(cl.hasOption('h')||(cl.hasOption('m')&&cl.hasOption('i')))){
					if(!cl.hasOption('i')){
						System.err.println("Interface not specified");
				    	System.exit(1);
					}
					if(!cl.hasOption('m')){
						System.err.println("Map file not specified");
				    	System.exit(1);
					}
				}					
				if ( cl.hasOption('h')) {
				    cliHelp(opt);
				    System.exit(0);
				}else {
				    if(cl.hasOption('i') && cl.hasOption('m')){
				    	String intf = cl.getOptionValue('i');
				    	if(intf.equalsIgnoreCase("swing")){
				    		swingInterface = true;
				    	}else if(intf.equalsIgnoreCase("console")){
				    		swingInterface = false;
				    	}else{	
				    		System.err.println("Wrong type of interface");
					    	System.exit(1);
				    	}	
				    	mapFile = cl.getOptionValue('m');
				    	CityLoaderFromTxtFile ctl = new CityLoaderFromTxtFile();
						FileInputStream ipt = new FileInputStream(mapFile);
						City city = ctl.loadCity(ipt);				
						engine = new RobotEngine(city, ctl.getPlaceArrayList().get(0),Direction.NORTH);
						if(swingInterface){					
							engine.setGUIWindow(new MainWindow(engine));							
							engine.setSwingInterface(swingInterface);
						}
						
						// plays
						engine.startEngine();	
						ipt.close();			    	
				    }else{
				    	System.err.println("Map file not specified");
				    	System.exit(1);
				    }
				}
				
				
				
				
			}catch(java.io.IOException e){
				//System.out.println(e.getMessage()+" " + e.toString());
				System.err.println("Error reading the map file: "+mapFile+" (No existe el fichero o el directorio)");
				System.exit(2);
			}catch(WrongCityFormatException e){
				//System.err.println("Error reading the map file: "+args[0]+" (El formato del mapa es incorrecto)");
				e.printStackTrace();
				System.exit(2);
			
			}
			
		
	}
	/**
	 * Show help for command line
	 */
	private static void cliHelp(Options opt){
		System.out.println("Execute this assignment with these parameters:");
		HelpFormatter f = new HelpFormatter();
		
	    f.printHelp("tp.pr4.Main [-h] [-i <type>] [-m <mapfile>]", opt);
	}
	/**
	 * Constant value for line separator
	 */
	public static String LINE_SEPARATOR = System.getProperty("line.separator");

}
